import { Injectable, Inject } from '@angular/core';

import { Observable } from 'rxjs/observable';
import { Store } from '@ngrx/store';
import { AppState } from '../entity/appState.model';
import { Orders } from '../entity/orders.model';
import * as OrdersActions from '../actions/orders.action';

// service
import { ToastService } from '../utils/toast.service';

// 常量
import * as Constant from '../../constant/constant';

/*** 订单相关服务
* */
// sdk 禾穆
declare const hmApi;
@Injectable()
export class OrdersService {
  constructor(
    private toastCtrl: ToastService,
    private store$: Store<AppState>,
  )
  { }

  /*** 获取借款store
   * */
  public getOrders(): Observable<Orders>
  {
    return this.store$.select(AppState => AppState.orders);
  }

  /*** 获取借款进度
   * 1.1 查询用户借款状态和历史记录API
   * */
  private getUserOrderHistory(): Promise<any>
  {
    return new Promise((resolve, reject) => {
      hmApi.getUserOrderHistory({},(err, result)=>{
        if(err) {
          reject(err);
          return;
        }
        // 返回
        resolve(result);
      });
    });
  }

  /*** 获取借款进度
   * 1.2 查询用户借款状态和历史记录
   * @param refresher Refresher
   * */
  public getUserOrderList(refresher): void
  {
    this.getUserOrderHistory().then(result=>{

      if(Array.isArray(result)&& result.length===0){
        if(refresher){ refresher.complete(); }
        this.store$.dispatch(new OrdersActions.GetUserOrdersFailedAction());
        return;
      }
      // 若获取成功
      if(refresher){ refresher.complete(); }
      this.store$.dispatch(new OrdersActions.GetUserOrdersSuccessAction(result));

    }).catch(err=> {
      if(refresher){ refresher.complete(); }
      this.toastCtrl.createCenterToast(Constant.SERVE_ERROR);
      console.log(err);
    });

  }

}
